package com.fyzk.activity.special.virtual_lottery;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.dialog.SeniorZhuiHaoActivity;
import com.fyzk.activity.lottery.gaopin.AnHuiK3Activity;
import com.fyzk.activity.lottery.gaopin.GD11x5Activity;
import com.fyzk.activity.lottery.gaopin.JLK3Activity;
import com.fyzk.activity.lottery.gaopin.JSK3Activity;
import com.fyzk.activity.lottery.gaopin.K3Activity;
import com.fyzk.activity.lottery.gaopin.KLSFActivity;
import com.fyzk.activity.lottery.gaopin.NXK3Activity;
import com.fyzk.activity.lottery.gaopin.SD11x5Activity;
import com.fyzk.activity.lottery.gaopin.SSCActivity;
import com.fyzk.activity.lottery.shuzicai.DLTActivity;
import com.fyzk.activity.lottery.shuzicai.FC3DActivity;
import com.fyzk.activity.lottery.shuzicai.PL3Activity;
import com.fyzk.activity.lottery.shuzicai.PL5Activity;
import com.fyzk.activity.lottery.shuzicai.QLCActivity;
import com.fyzk.activity.lottery.shuzicai.QXCActivity;
import com.fyzk.activity.lottery.shuzicai.SSQActivity;
import com.fyzk.activity.user.xiangxi.JCOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.OldFootballOrderDetailActivity;
import com.fyzk.activity.zhifu.BetBaseActivity;
import com.fyzk.activity.zhifu.NumLotteryZhiFuAdapter;
import com.fyzk.bean.BetResponse;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.betcode.BetLotteryInfo;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.dialog.SureDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.random.RandomFactory;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.ASView;
import com.fyzk.view.ViewCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/1/5.
 *
 *  虚拟彩种数字彩支付界面
 */

public class Virtual_NumLotteryZhiFuActivity extends BetBaseActivity implements
        NumLotteryZhiFuAdapter.NumLotteryZhiFuOnClick, ViewCallBack.CountDownInterface, ASView.OnValueChangedLisener {

    private final String TAG = this.getClass().getSimpleName();

    private TextView ziXuan;
    private TextView jiXuan;

    private ListView listView;
    private NumLotteryZhiFuAdapter adapter;

    private LinearLayout prizeStop_ll;
    private CheckBox isPrizeStop_tv;
    private CheckBox szc_zhifu_zhuijia;
    private TextView senior_zhuiHao;

    private ASView zhuiHao;
    private ASView touBei;

    private List<BetLotteryInfo> infos = new ArrayList<BetLotteryInfo>();
    private BetLotteryInfo betInfor = new BetLotteryInfo();

    private SureDialog myDialog_ok = null;

    public static boolean isZhiFuBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ViewCallBack.getInstance().AttachCountDownObj(this);
        lotteryId = getIntent().getIntExtra(IntentParamUtils.LOTTERYID, 0);
        betInfor = (BetLotteryInfo) getIntent().getSerializableExtra("bet");

    }

    @Override
    protected void onResume() {
        super.onResume();
        infos = AppLotteryCodeListManager.getInstance().getList();
        adapterChange();
        isZhiFuBack = false;
        if (infos != null && infos.size() > 0) {
            BetLotteryInfo betInfor1 = infos.get(0);
            betInfor.wcodeID = betInfor1.wcodeID;
            betInfor.codeNum = betInfor1.codeNum;
            betInfor.zhushu = betInfor1.zhushu;
            betInfor.arr_infos = betInfor1.arr_infos;
            betInfor.popupID = betInfor1.popupID;

        } else {
        }
        setSeniorZhuiHaoImg();
    }

    private void setSeniorZhuiHaoImg() {
        Drawable img_Left;
        Resources res = getContext().getResources();
        int img_id;
        if (phases.equals("") || beiShus.equals("")) {
            img_id = R.drawable.btn_xing_no;
            phases = "";
            beiShus = "";
            isGaoJiZhuiHao = false;
        } else {
            isGaoJiZhuiHao = true;
            img_id = R.drawable.btn_xing;
        }
        img_Left = res.getDrawable(img_id);
        img_Left.setBounds(0, 0, img_Left.getMinimumWidth(),
                img_Left.getMinimumHeight());
        senior_zhuiHao.setCompoundDrawables(img_Left, null, null, null);
        setBtmView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == 0 && data != null) {
            phases = data
                    .getStringExtra(IntentParamUtils.SENIOR_ZHUIHAO_PHASES);
            beiShus = data
                    .getStringExtra(IntentParamUtils.SENIOR_ZHUIHAO_BEISHUS);
            beishu = data.getIntExtra(IntentParamUtils.MULTIPLE, 1);
            touBei.setValue(beishu);

            String[] qis = phases.split(",");
            zhuiQi_GaoJi = qis.length;
        }

    }

    @Override
    protected void clear() {
        // TODO Auto-generated method stub
        if (infos.size() > 0) {
            infos.clear();
        }
    }

    private int oneAmount = 2;


//    @Override
//    public int getLotteryId() {
//        // TODO Auto-generated method stub
//        return getIntent().getIntExtra(IntentParamUtils.LOTTERYID, 0);
//    }


    @Override
    protected View initCenterView() {
        // TODO Auto-generated method stub
        infos = AppLotteryCodeListManager.getInstance().getList();

        View view = LayoutInflater.from(this).inflate(
                R.layout.dj_layout_numzhifu, null);
        ziXuan = (TextView) view.findViewById(R.id.szc_zhifu_center_zixuan);
        jiXuan = (TextView) view
                .findViewById(R.id.szc_zhifu_center_jixuan1);
        listView = (ListView) view.findViewById(R.id.szc_zhifu_listview);
        prizeStop_ll = (LinearLayout) view
                .findViewById(R.id.szc_zhifu_isprizestop_ll);
        isPrizeStop_tv = (CheckBox) view
                .findViewById(R.id.szc_zhifu_isprizestop);
        szc_zhifu_zhuijia = (CheckBox) view.findViewById(R.id.szc_zhifu_zhuijia);
        senior_zhuiHao = (TextView) view.findViewById(R.id.szc_zhifu_senior);

        zhuiHao = (ASView) view
                .findViewById(R.id.szc_zhifu_zhuiqi);
        zhuiHao.setLeftText("追");
        zhuiHao.setRightText("期");
        if (lotteryId == LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT
                || lotteryId == LotteryIDUtils.CQSSC_LOTTERY_ID_INT
                || lotteryId == LotteryIDUtils.NXK3_LOTTERY_ID_INT
                || lotteryId == LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT) {
            zhuiHao.setMax(100);
            zhuiHao.setTiShi("最多可追100期");
        } else {
            zhuiHao.setMax(10);
            zhuiHao.setTiShi("最多可追10期");
        }
        zhuiHao.setOnValueChangedLisener(this);


        if(lotteryId == LotteryIDUtils.DLT_LOTTERY_ID_INT){
            szc_zhifu_zhuijia.setVisibility(View.VISIBLE);
        }else{
            szc_zhifu_zhuijia.setVisibility(View.GONE);
        }

        touBei = (ASView) view
                .findViewById(R.id.szc_zhifu_beishu);
        touBei.setLeftText("投");
        touBei.setRightText("倍");
        touBei.setOnValueChangedLisener(this);

        isPrizeStop_tv
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        // TODO Auto-generated method stub
                        isPrizeStop = isChecked;
                    }
                });

        szc_zhifu_zhuijia.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    isZhuijia = true;
                    oneAmount = 3;
                } else {
                    oneAmount = 2;
                    isZhuijia = false;
                }
                adapter.setOneAmount(oneAmount);
                adapter.notifyDataSetChanged();
                setBtmView();
            }
        });

        // 高级追号
        senior_zhuiHao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getContext(),
                        SeniorZhuiHaoActivity.class);
                intent.putExtra(IntentParamUtils.LOTTERYID, lotteryId);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_NUM, zhuiQi);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_PRIZESTOP, isPrizeStop);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_ADDITION, isZhuijia);
                intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_BETCODE, getBetCode());
                intent.putExtra(IntentParamUtils.MULTIPLE, getBeishu());
                intent.putExtra(IntentParamUtils.AMT, getAmt());
                startActivityForResult(intent, 0);
            }
        });

        if (adapter == null) {
            adapter = new NumLotteryZhiFuAdapter(getContext(), infos,
                    getOneAmount());
            adapter.setListener(this);
        }
        listView.setAdapter(adapter);
        listView.setItemsCanFocus(false);

        ziXuan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fromZhiFuBack(-1);
            }
        });

        jiXuan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 机选1注
                if (betInfor != null) {
                    try {
                        RandomFactory.getRandom(lotteryId)
                                .randomYiZhu(betInfor);
                        adapterChange();
                    } catch (Exception e) {
                        AppToast.getToast().show("该彩种暂无机选" + lotteryId);
                    }
                } else {
                    // Toast.makeText(getContext(), "betInfor = null",
                    // 2000).show();
                }
                setBtmView();
            }
        });

        return view;
    }

    private void fromZhiFuBack(int position) {
        Intent intent;
        switch (lotteryId) {
            case LotteryIDUtils.SSQ_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SSQActivity.class);
                break;
            case LotteryIDUtils.DLT_LOTTERY_ID_INT:
                intent = new Intent(getContext(), DLTActivity.class);
                break;
            case LotteryIDUtils.PL3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), PL3Activity.class);
                break;
            case LotteryIDUtils.PL5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), PL5Activity.class);
                break;
            case LotteryIDUtils.FC3D_LOTTERY_ID_INT:
                intent = new Intent(getContext(), FC3DActivity.class);
                break;
            case LotteryIDUtils.QXC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), QXCActivity.class);
                break;
            case LotteryIDUtils.QLC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), QLCActivity.class);
                break;
            case LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SD11x5Activity.class);
                break;
            case LotteryIDUtils.CQSSC_LOTTERY_ID_INT:
                intent = new Intent(getContext(), SSCActivity.class);
                break;
//		case LotteryIDUtils.JXSSC_LOTTERY_ID_INT:
//			intent = new Intent(getContext(), JXSSCActivity.class);
//			break;
            case LotteryIDUtils.NXK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), NXK3Activity.class);
                break;
            case LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), AnHuiK3Activity.class);
                break;
            case LotteryIDUtils.JSK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), JSK3Activity.class);
                break;
            case LotteryIDUtils.JLK3_LOTTERY_ID_INT:
                intent = new Intent(getContext(), JLK3Activity.class);
                break;
            case LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT:
                intent = new Intent(getContext(), GD11x5Activity.class);
                break;
            case LotteryIDUtils.KLSF_LOTTERY_ID_INT:
                intent = new Intent(getContext(), KLSFActivity.class);
                break;
            default:
                intent = null;
                break;
        }
        if (intent != null) {
            isZhiFuBack = true;
            intent.putExtra("id", position);
            startActivity(intent);
        }
    }

    @Override
    protected void adapterChange() {
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        // adapter.notifyDataSetChanged();
    }

//    @Override
//    protected void zhifu_ok(String tips) {
//        // TODO Auto-generated method stub
//
//        if(myDialog_ok == null){
//            myDialog_ok = new SureDialog(this,sureDialogClickListner,"",tips,"查看详情","返回");
//        }
//
//        myDialog_ok.show();
//    }

    SureDialog.OnDialogOKCancleClickListener sureDialogClickListner = new SureDialog.OnDialogOKCancleClickListener() {

        @Override
        public void onOKClick() {
//
//			// TODO Auto-generated method stub
//			myDialog_ok.dismiss();
//			Intent intent;
//			if (zhuiQi > 1) {
//				intent = new Intent(getContext(), ZhuihaoDetailActivity.class);
//				intent.putExtra(IntentParamUtils.BETDETAILID,
//						responseObj_zhuiHao.orderId);
//			} else {
//				intent = new Intent(getContext(), NumLotteryOrderDetailActivity.class);
//				intent.putExtra(IntentParamUtils.BETDETAILID, responseObj.id);
//			}
//			startActivity(intent);
//			NumLotteryZhiFuActivity.this.finish();
        }

        @Override
        public void onCancleClick() {
            // TODO Auto-generated method stub
            clear();
            myDialog_ok.dismiss();
            Virtual_NumLotteryZhiFuActivity.this.finish();
        }

    };

    @Override
    public int getZhushu() {
        // TODO Auto-generated method stub
        int amount = 0;
        for (BetLotteryInfo info : infos) {
            amount += info.zhushu;
        }
        return amount;
    }

    @Override
    public int getOneAmount() {
        // TODO Auto-generated method stub
        return oneAmount;
    }

    @Override
    public String getBetCode() {

        StringBuffer sb = new StringBuffer();
        for (BetLotteryInfo info : infos) {
            if (info.wcodeID == K3Activity.K3_LOTTERY_SUMZHI_ID_INT) {
                String firstCode = info.codeNum.charAt(0) + "";
                if (firstCode.equals("3")) {
                    sb.append(K3Activity.K3_LOTTERY_SANTONGHAO_ID_INT);//
                    sb.append("-1,1,1^!");
                    if (info.codeNum.length() > 1) {
                        info.codeNum = info.codeNum.substring(2,
                                info.codeNum.length());
                    } else {
                        continue;
                    }
                }
                if (info.codeNum.contains("18")) {
                    sb.append(K3Activity.K3_LOTTERY_SANTONGHAO_ID_INT);//
                    sb.append("-6,6,6^!");
                    if (info.codeNum.length() > 1) {
                        info.codeNum = info.codeNum.substring(0,
                                info.codeNum.length() - 3);
                    } else {
                        continue;
                    }
                }

            }
            sb.append(info.wcodeID);// 200302-01,08|07,08|00|02|03^
            sb.append("-");
            sb.append(info.codeNum);
            sb.append("^!");
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    @Override
    public void onClickDelete(int position) {
        // TODO Auto-generated method stub
        infos.remove(position);
        adapterChange();
        setBtmView();
    }

    @Override
    public void onClickChange(int position) {
        // TODO Auto-generated method stub
//		fromZhiFuBack(position);
    }

    @Override
    public void countDown() {
        // TODO Auto-generated method stub
        if ( !AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.SD11xuan5_Period + lotteryId)
                && lotteryId == LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT
                && AppLotteryInfos.SD11xuan5_endTime <= 0
                && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.SD11xuan5_Period, "");
        }
        if ( !AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.GD11xuan5_Period + lotteryId)
                && lotteryId == LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT
                && AppLotteryInfos.GD11xuan5_endTime <= 0
                && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.GD11xuan5_Period, "");
        }

        if (!AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.GpSSC_Period + lotteryId)
                && lotteryId == LotteryIDUtils.CQSSC_LOTTERY_ID_INT
                && AppLotteryInfos.GpSSC_endTime <= 0 && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.GpSSC_Period, "");
        }

        if (!AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.AnHuiK3_Period + lotteryId)
                && lotteryId == LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT
                && AppLotteryInfos.AnHuiK3_endTime <= 0
                && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.AnHuiK3_Period, "");
        }
        if (!AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.JSK3_Period + lotteryId)
                && lotteryId == LotteryIDUtils.JSK3_LOTTERY_ID_INT
                && AppLotteryInfos.JSK3_endTime <= 0
                && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.JSK3_Period, "");
        }
        if (!AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.JLK3_Period + lotteryId)
                && lotteryId == LotteryIDUtils.JLK3_LOTTERY_ID_INT
                && AppLotteryInfos.JLK3_endTime <= 0
                && this.hasWindowFocus()) {
            showEndTimeDialog(AppLotteryInfos.JLK3_Period, "");
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ViewCallBack.getInstance().DettachCountDownObj(this);
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        ViewCallBack.getInstance().DettachCountDownObj(this);
    }

    @Override
    public void onValueChanged(ASView view,int value) {
        switch (view.getId()){
            case R.id.szc_zhifu_zhuiqi:
                zhuiQi = value;
                break;
            case R.id.szc_zhifu_beishu:
                beishu = value;
                break;
        }
        setBtmView();
    }

    @Override
    protected void bet() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", getBetCode());
            params.put("lotteryType", lotteryId);
            params.put("phase", getPeriod());
            params.put("amount", getOneAmount() * getBeishu() * 100 * getZhushu());
            params.put("multiple", getBeishu());
            params.put("oneAmount", getOneAmount() * 100);
            params.put("prizeOptimize", "0");//prizeOptimize奖金诱惑（优化：1；普通：0）
            params.put("codeFilter", "0");//codeFilter旋转过滤（过滤：1；普通：0）
            params.put("userCouponId", "");//优惠劵Id，非优惠劵投注可以不写
            httpPostJson(CommandUtil.VIRTUALBET, Commands.VIRTUALBET, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        DJ_ProgressDialog.dissmiss();
        switch (requestCode) {
            case CommandUtil.VIRTUALBET:
                if (resultBean.getErrorcode().equals("0")) {
                    final String orderId = JSON.parseObject(resultBean.getData(), BetResponse
                            .class).getOrderid();
                    final String lotteryType = lotteryId + "";
                    new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("虚拟投注成功")
                            .setPositiveButton
                                    ("查看订单", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                            clear();
                                            Intent intent;
                                            if (lotteryType.contains("30") || lotteryType
                                                    .contains("50")) {
                                                intent = new Intent(getContext(),
                                                        JCOrderDetailActivity
                                                                .class);
                                            } else if (lotteryType.contains("40")) {
                                                intent = new Intent(getContext(),
                                                        OldFootballOrderDetailActivity.class);
                                            } else {
                                                intent = new Intent(getContext(),
                                                        VirtualBetDetailActivity.class);

                                            }
                                            intent.putExtra(IntentParamUtils.BETDETAILID, orderId);
                                            getContext().startActivity(intent);
                                            finish();
                                        }

                                    }).setNegativeButton("完成", new DialogInterface
                            .OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            clear();
                            dialog.cancel();
                            setResult(0x6);
                            finish();
                        }
                    }).create().show();


                } else {
                    showToast(resultBean.getMsg());
                }
                break;

        }
    }
}
